<script setup>
import ChartItem from "../components/chart/ChartItem.vue";
</script>

<template>
  <div id="home" class="home">
    <el-container class="el-container">
      <el-header :height="100" class="custom-header">
        <el-row>
          <el-button type="primary" size="small" @click="switchGrids();">
            <el-icon v-if="!isGrids" size="large"><Menu/></el-icon>
            <el-icon v-else size="large"><home-filled/></el-icon>
          </el-button>
          <el-button type="primary" size="small" @click="testBackClick()">
            回测
          </el-button>
          <el-button type="primary" size="small" @click="openEvent()">{{xaxisimpOpen?'关闭':'打开'}}分割线</el-button>
          <el-select class="home_select" v-model="timezone" placeholder="" size="small" style="width: 120px">
            <el-option v-for="{text,value} in timezones" :key="value" :label="text" :value="value"/>
          </el-select>
        </el-row>
      </el-header>
      <el-main>
      <ChartItem :id="'chart_main'" :timezone="timezone"  :open="xaxisimpOpen" :switchOverlay="openInfoId == 'chart_main' ?switchOverlay:{}"  v-if="!isGrids" :union="isGrids" @open="openOverlaysListEvent"></ChartItem>
      <div class="grids" v-else>
        <div class="grids_item" v-for="i in 4" :key="i">
          <ChartItem :id="'chart_main_' + i" :timezone="timezone" :open="xaxisimpOpen" :switchOverlay="openInfoId == ('chart_main_' + i) ?switchOverlay:{}" :union="isGrids" :syncOverlayColor="syncOverlayColor" @overlay-color-change="syncOverlayColor = $event" @open="openOverlaysListEvent"></ChartItem>
        </div>
      </div>
      </el-main>
    </el-container>
    <el-dialog v-model="openStore" title="笔记管理"  @close="overlayStoreClose()">
      <template #header>
        <el-row>
          <el-col :span="16">笔记管理</el-col>
          <el-col :span="8">
            <div class="stores_title_btns">
              <el-button size="small" @click="importStore()"  type="primary">导入</el-button>
            </div>
          </el-col>
        </el-row>
      </template>
      <el-table :data="overlayStoreList">
        <el-table-column property="index" label="序号"/>
        <el-table-column property="storeName" label="笔记名称"/>
        <el-table-column property="originDepend" label="创建于(品种/周期)"/>
        <el-table-column property="depends" label="关联的品种/周期" />
        <el-table-column align="center" width="300">
          <template #header>
            功能
          </template>
          <template #default="scope">
            <el-button size="small" v-if="scope.row.depends.split('\r\n').indexOf(`${openInfo.goods} ${openInfo.period}`) < 0" @click="addDepend(scope.$index, scope.row)" type="primary">挂载</el-button>
            <el-button size="small" v-else @click="removeDepend(scope.$index, scope.row)" type="info">卸载</el-button>
            <el-button size="small" @click="switchLock(scope.$index, scope.row)" type="warning">{{overlayStoreList[scope.$index].lock?'已锁定':'锁定'}}</el-button>
            <el-button size="small" @click="remove(scope.$index, scope.row)" type="danger">删除</el-button>
            <el-button size="small" @click="exportStore(scope.$index, scope.row)" type="warning">导出</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'pinia'
import { crosshair,charts,currentChartId } from '../store.js' 
import {setXAxisImpOPen } from "klinecharts";
import localStore from '../localStore.js';
import { ElMessageBox,ElMessage } from 'element-plus'

export default{
  data(){
    return{
      isGrids:false,
      timezone:'Africa/Bujumbura',
      timezones:[
        {text:'UTC+13',value:'Pacific/Apia'},
        {text:'UTC+12',value:'Asia/Anadyr'},
        {text:'UTC+11',value:'Asia/Magadan'},
        {text:'UTC+10',value:'Asia/Vladivostok'},
        {text:'UTC+9',value:'Asia/Chita'},
        {text:'UTC+8',value:'Hongkong'},
        {text:'UTC+7',value:'Asia/Bangkok'},
        {text:'UTC+6',value:'Asia/Bishkek'},
        {text:'UTC+5',value:'Asia/Almaty'},
        {text:'UTC+4',value:'Asia/Dubai'},
        {text:'UTC+3',value:'Africa/Asmara'},
        {text:'UTC+2',value:'Africa/Bujumbura'},
        {text:'UTC+1',value:'Africa/Algiers'},
        {text:'UTC+0',value:'Africa/Accra'},
        {text:'UTC-1',value:'Atlantic/Cape_Verde'},
        {text:'UTC-2',value:'America/Noronha'},
        {text:'UTC-3',value:'America/Araguaina'},
        {text:'UTC-4',value:'America/Anguilla'},
        {text:'UTC-5',value:'America/Bogota'},
        {text:'UTC-6',value:'America/Monterrey'},
        {text:'UTC-7',value:'America/Dawson'},
        {text:'UTC-8',value:'Pacific/Pitcairn'},
        {text:'UTC-9',value:'Pacific/Gambier'},
        {text:'UTC-10',value:'Pacific/Johnston'},
      ],
      xaxisimpOpen:false,
      syncOverlayColor:undefined,
      openStore:false,
      openInfo:undefined,
      overlayStores:[],
      switchOverlay:{},
    }
  },
  computed:{
    ...mapState(crosshair, ['crosshair']),
    ...mapState(charts, ['charts']),
    ...mapState(currentChartId, ['currentChartId']),
    overlayStoreList(){
      if(!this.openInfo || !this.overlayStores) return [];
      let list = JSON.parse(JSON.stringify(this.overlayStores));
      list = list.map((v,i,arr) => {
        return({
          storeName:v.storeName,
          depends:v.depends.map(dep => `${dep.goods} ${dep.period}`).join('\r\n'),
          pkId:v.pkId,
          lock:!!v.lock,
          originDepend:`${v.originDepend.goods} ${v.originDepend.period}`
        })
      });
      list.sort(v => v.depends.indexOf(`${this.openInfo.goods} ${this.openInfo.period}`));
      return list.map((v,i) => ({...v,index:i+1}));
    },
    openInfoId(){
      if(this.openInfo){
        return this.openInfo.id;
      }
      else{
        return undefined;
      }
    }
  },
  methods:{
    testBackClick(){
      if(window.electron){
        electron.openNewWindow && electron.openNewWindow('/testback/commit');
      }
      else{
        let originUrl = location.href.match(/^[^]*\#/)[0];
        window.open(`${originUrl}/testback/commit`,'','popup=true');
      }
    },
    switchGrids(){
      this.isGrids = !this.isGrids;
    },
    syncOverlayColorEvent(e){
      console.log(e)
    },
    openEvent(){
      this.xaxisimpOpen = !this.xaxisimpOpen;
      setXAxisImpOPen(this.xaxisimpOpen);
    },
    openOverlaysListEvent(opts){
      this.openStore = true;
      this.openInfo = opts;
      this.overlayStores = this.getOverlayStores({type:'all'});
      
    },
    getOverlayStores(opts){
      if(opts && opts.type == 'all'){
        return JSON.parse(localStore.getItem(this.openInfo.saveId));
      }
      let overlays = JSON.parse(localStore.getItem(this.openInfo.saveId));
      overlays = overlays.filter(overlay => {
        if(!!overlay.depends){
          let depends = overlay.depends;
          if(!!depends.find(dep => (dep.pkId ==  this.openInfo.pkId && dep.period == this.openInfo.period))){
            return true;
          }
          else{
            return false;
          }
        }
        return false;
      })
      return overlays;
    },
    addDepend(index,row){
      //row.storeName
      this.overlayStores.forEach(store => {
        if(store.storeName == row.storeName){
          store.depends.push({
            goods:this.openInfo.goods,
            period:this.openInfo.period,
            pkId:this.openInfo.pkId,
          });
        }
      });
      localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
      this.$nextTick(() => {      
        this.switchOverlay = {
          action:'add',
          storeName:row.storeName,
        }
      });
    },
    removeDepend(index,row){
      //row.storeName
        let deps = row.depends.split(' \r\n');
          this.overlayStores.forEach(store => {
            
          if(store.storeName == row.storeName){
              store.depends = store.depends.filter(dep => !(dep.goods == this.openInfo.goods && dep.period == this.openInfo.period));
            }
          });
          localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
          this.$nextTick(() => {      
            this.switchOverlay = {
              action:'remove',
              storeName:row.storeName,
            }
          });
    },
    remove(index,row){
      //row.storeName
      ElMessageBox.confirm(`确认删除 （${row.storeName}） 笔记?`,{
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          showCancelButton: false	
        })
        .then(() => {
          this.overlayStores = this.overlayStores.filter(v => v.storeName != row.storeName);
          localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
        })
        .catch(() => {});
    },
    exportStore(index,row){
      // {
      // data:data,
      // filters:[{name:'JSON',extensions:['json']}]
      // }
      let overlayStore =  this.overlayStores.find(v => v.storeName == row.storeName);
      if(window.electron){
        window.electron.saveFile({
          data:JSON.stringify({...overlayStore,id:undefined}),
          fileName:overlayStore.storeName,
          filters:[{name:'JSON',extensions:['json']}]
        })
      }
      else{
        ElMessage({
            message: '暂不支持',
            type: 'error',
        });
        return;
      }
    },
    async importStore(){
      let possibleStores = [];
      const addStore = async (fileContents,index) => {
        let fileContent = fileContents[index];
        let filePath = fileContent.filePath;
        let content = fileContent.content;
        if(!!this.overlayStores.find( overlayStore => overlayStore.storeName == content.storeName)){
          //存在，覆盖?
          try{
            await ElMessageBox.confirm(`确认覆盖 （${content.storeName}） 笔记?`,'',{
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: false	
            });
            possibleStores.push(content.storeName);
            this.overlayStores = this.overlayStores.filter(overlayStore => overlayStore.storeName != content.storeName);
            this.overlayStores.push(content);
            localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
          }
          catch(e){}

        }
        else{
          this.overlayStores.push(content);
          localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
        }
        this.overlayStores = this.getOverlayStores({type:'all'});
        if(index < fileContents.length - 1){
          addStore(fileContents, index + 1);
        }
        else{
          this.switchOverlay = {
            action:'update',
            possibleStores:[...new Set(possibleStores)]
          }
        }
      }
      if(window.electron){
        let result = await window.electron.readFiles([{name:'JSON',extensions:['json']}],true);
        if(!result.canceled){
          let fileContents = result.fileContents;
          addStore(fileContents,0);
        }
      }
      else{
         ElMessage({
             message: '暂不支持',
             type: 'error',
         });
      }
    },
    switchLock(index,row){
      //row.storeName
      this.overlayStores = this.overlayStores.map(v => {
        if(v.storeName == row.storeName){
            return({...v,lock:!v.lock})
        }
        else{
          return v;
        }
      });
      localStore.setItem(this.openInfo.saveId,JSON.stringify(this.overlayStores));
    },
    overlayStoreClose(){
      this.openInfo = undefined;
      this.switchOverlay = {};
    }
  },
  watch:{
    crosshair(newVal,oldVal){
      if(!this.isGrids) return;
      if(!newVal) return; 
      for(let i = 0; i < this.charts.length; i++){
        const chart = this.charts[i];
        if(chart.id != this.currentChartId){
          chart.getChartStore().getCrosshairStore().setFromData(newVal);
        }
      }
    }
  }
}
</script>

<style scoped>
body {
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #f2f3f5;
}

div,
p {
  box-sizing: border-box;
}

p {
  margin: 0;
}

.home {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex-wrap: wrap;
}
.el-container{
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
.custom-header{
  padding: 10px 20px;
  padding-bottom: 0px;
}
.home_select{
  padding-left: 10px;
}

.grids{
  display: grid;
  /* grid-template-rows:50% 50%;
  grid-template-columns:50% 50%; */
  column-gap:0;
  /* 横向等比分割 */
  justify-content: space-evenly;
  /* 纵向等比分割 */
  align-content: space-evenly;
  grid-template-columns: repeat(2, 50%);
  grid-template-rows: repeat(2, 50%);
  width: 100%;
  height: 100%;
}
.grids_item{
  border-right: 1px solid rgba(212, 203, 203, 0.534);
  border-bottom: 1px solid rgba(212, 203, 203, 0.534);
}
.stores_title_btns{
  display: flex;
  justify-content:flex-end;
}
</style>
